<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { accountFormSchema } from './user.data';
  import {
    getBranchList,
    getRoleListByBranch,
    createUser,
    updateUser,
    initpwdcheck,
  } from '/@/api/system/system';
  import { encryptByRsa } from '/@/utils/cipher';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const isUpdate = ref(true);
      const rowId = ref('');

      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          rowId.value = data.record.roleCode;
          setFieldsValue({
            ...data.record,
          });
          const roles = data.record.roles ? data.record.roles.map((data) => data.roleCode) : [];
          setFieldsValue({ roles: roles || [] });

          getRoleListByBranch({ branchInnercode: data.record.roleCode }).then((res) => {
            let data: any = [];
            res.forEach((val) => {
              data.push({ value: val.roleCode, label: val.roleName });
            });
            updateSchema({
              field: 'roles',
              componentProps: {
                mode: 'multiple',
                options: data,
              },
            });
          });
        } else {
          const passwordVeriry = await initpwdcheck();
          updateSchema({
            field: 'password',
            dynamicRules: () => {
              return [
                {
                  required: true,
                  // @ts-ignore
                  validator: async (rule, value) => {
                    if (!value) {
                      /* eslint-disable-next-line */
                      return Promise.reject('请输入密码');
                    }
                    if (
                      value.length < passwordVeriry.minLen ||
                      value.length > passwordVeriry.maxLen
                    ) {
                      return Promise.reject(
                        `必须是${passwordVeriry.minLen}-${passwordVeriry.maxLen}位的字符`
                      );
                    }
                    return Promise.resolve();
                  },
                  trigger: 'change',
                },
              ];
            },
          });
        }

        const treeData = await getBranchList({ isSelect: 'Y' });
        updateSchema([
          {
            field: 'password',
            ifShow: !unref(isUpdate),
          },
          {
            field: 'confirmPassword',
            ifShow: !unref(isUpdate),
          },
          {
            field: 'branchInnercode',
            componentProps: ({ formActionType, formModel }) => {
              return {
                treeData,
                onChange: (value: any) => {
                  // 根据机构来刷新机构管理员下拉框列表数据
                  getRoleListByBranch({ branchInnercode: value }).then((res) => {
                    let data: any = [];
                    res.forEach((val) => {
                      data.push({ value: val.roleCode, label: val.roleName });
                    });
                    const { updateSchema } = formActionType;
                    updateSchema({
                      field: 'roles',
                      componentProps: {
                        mode: 'multiple',
                        options: data,
                      },
                    });
                    formModel.roles = [];
                  });
                },
              };
            },
          },
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          if (values.roles) {
            values.roles = values.roles.join();
          }
          if (!unref(isUpdate)) {
            values.password = encryptByRsa(values.password);
            values.confirmPassword = encryptByRsa(values.confirmPassword);
          }
          unref(isUpdate) ? await updateUser(values) : await createUser(values);
          closeModal();
          unref(isUpdate)
            ? createMessage.success('账号添加成功')
            : createMessage.success('账号修改成功');

          emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
